package com.ck567.springbootnettyprotobufjava.codec;


import com.ck567.springbootnettyprotobufjava.message.Message;
import com.ck567.springbootnettyprotobufjava.utils.OptionType;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @description: 信息解码器
 * * *  数据包格式
 * * * +——-----——+——-------——+
 * * * |  类型(2)|     数据   |
 * * *+——-----——+——-------——+
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class MessageDecoder extends MessageToMessageDecoder<WebSocketFrame> {

    private final MessageCodecFactory codecFactory;

    @Autowired
    public MessageDecoder(MessageCodecFactory codecFactory) {
        this.codecFactory = codecFactory;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, WebSocketFrame msg, List<Object> out) throws Exception {

        ByteBuf buf = msg.content();
        // 读取操作数
        short type = buf.readShort();
        // 读取数据体
        int readableBytes = buf.readableBytes();
        byte[] data = new byte[readableBytes];
        buf.readBytes(data);
        OptionType optionType = OptionType.getType(type);
        // 消息类型解码
        Message message = codecFactory.decodeMessage(optionType, data);
        out.add(message);
    }

}
